//
//  RCGCDAsyncSocket.m
//  RCNetRequestProject
//
//  Created by kabu on 2017/8/18.
//  Copyright © 2017年 RC. All rights reserved.
//

#import "RCGCDAsyncSocket.h"
#import "GCDAsyncSocket.h"
#import "RCSocketSendSerializationer.h"
#import "RCSocketAcceptSerializationer.h"
@interface RCGCDAsyncSocket()<GCDAsyncSocketDelegate>
@property (nonatomic, strong) GCDAsyncSocket*clinetSocket;
@property (nonatomic, copy) RCConnectSocketCallBack connectCallBack;
@property (nonatomic, copy) RCServerSocketCallBack serverCallBack;

@end
@implementation RCGCDAsyncSocket

- (instancetype) init{
    self = [super init];
    if (self) {
        self.clinetSocket=[[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    }
    return self;
}
-(void)setRCServerSocketCallBack:(RCServerSocketCallBack)aCallback{
    _serverCallBack = aCallback;
}
- (void) connectIP:(NSString *)ip port:(int)aPort callBack:(RCConnectSocketCallBack)aCallBack{
    
    _connectCallBack =aCallBack;
    NSError *error;

    BOOL result= [self.clinetSocket connectToHost:ip onPort:aPort error:&error];
    if (result&&error==nil) {
        NSLog(@"连接成功");
        
    }else{
        NSLog(@"连接失败");
        if (_connectCallBack) {
            _connectCallBack(nil, [NSError errorWithDomain:@"connect faile" code:-100 userInfo:nil]);
        }
    }
}
- (NSData*)read:(uint8_t)buf{
    [self.clinetSocket readDataWithTimeout:-1 tag:0];
    return nil;
}
- (NSInteger) write:(id)message{
    NSData *data = [self.senderSerializationer transformMessageToData:message];
    [self.clinetSocket writeData:data withTimeout:-1 tag:0];
    return 1;
}
#pragma mark GCDAsyncSocketDelegate
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    NSLog(@"链接成功 host: %@",host);
    [self.clinetSocket readDataWithTimeout:-1 tag:0];
    if (_connectCallBack) {
        _connectCallBack(nil,nil);
    }
    
}
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    
}
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    NSLog(@"write tag %li",tag);
}
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
//    NSString*text = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    NSData *result = [self.acceptSerializationer transformMessageToResult:data];
    if (_serverCallBack) {
        _serverCallBack(result,nil);
    }
    [self.clinetSocket readDataWithTimeout:-1 tag:0];
}
@end
